<template>
  <div>
    <div class="date-picker"
         @click="handleTypeSelect">
      <text class="icon text-warning mr-1">&#xe65e;</text>
      <text class="search-text"
            :class="[searchTypeIsSelect&&'text-success']">{{searchTypeLabel}}</text>
    </div>

    <vm-status v-if="showStatus"
               empty-text="暂无数据"
               :type="totalPages === -1 ? 'error' : 'empty'"></vm-status>

    <list ref="list"
          :showRefresh="true"
          :showLoadMore="showLoadMore"
          @refresh="refresh('list')"
          @loadMore="loadmore('list')"
          loadmoreoffset="100">

      <cell v-for="(item, index) in data"
            :key="index">
        <div class="bg-white">
          <div class="account-item">
            <text class="account-date">{{item.dateStr}}</text>
            <div class="flex-row">
              <text class="account-date">{{item.typeStr}}: {{item.fundsStr}}</text>
            </div>
          </div>
          <div v-for="(record, serial) in item.records"
               :key="serial"
               class="flex-row">
            <image class="account-icon"
                   :src="record.icon"></image>
            <div class="account-main"
                 :class="[record.isLast&&'account-main-last']">
              <text class="account-remark"
                    :class="[record.isIn?'text-success':'text-error']">{{record.remarkStr}}</text>
              <!-- <text class="account-number"
                    :class="[record.isIn?'text-success':'text-error']">{{record.account_funds}}</text> -->
            </div>
          </div>
        </div>
      </cell>

    </list>
  </div>
</template>
<script>
import VmStatus from '../../components/vm-status.vue'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import { convert, enumRecordType } from './convert'
import { calcNumber, fillByChar, getDaysInMonth } from '../../plugins/utils'

export default {
  components: {
    VmStatus
  },
  props: {},
  data() {
    return {
      farm: {},
      params: {
        index: 1,
        size: 10,
        'account_record_type.eq': 1,
        'farm_id.eq': '',
        'account_date.gte': '',
        'account_date.lte': ''
      },
      totalPages: 2,
      data: []
    }
  },
  computed: {
    showLoadMore() {
      return this.totalPages > this.params.index
    },
    searchTypeLabel() {
      let res = this.params['account_date.gte'].substr(0, 10)
      let end = this.params['account_date.lte']
      if (end) {
        end = end.substr(0, 10)
        res += ` ~ ${end}`
      }
      return res || '按时间查询'
    },
    searchTypeIsSelect() {
      return true
    },
    showStatus() {
      return this.totalPages === -1 || !this.data.length
    },
    typeStr() {
      return enumRecordType[this.params['account_record_type.eq']]
    }
  },
  watch: {},
  created() {
    this.getFarm()
  },
  mounted() { },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.params['farm_id.eq'] = this.farm.id
        this.getParams()
      }
    },
    getParams() {
      this.$router.getParams().then(res => {
        let { type = 1, startDate, endDate } = res || {}
        this.params['account_record_type.eq'] = type

        // 时间
        if (!startDate || !endDate) {
          const nowDate = new Date()
          const year = nowDate.getFullYear()
          const month = nowDate.getMonth() + 1
          const yearMonthStr = `${year}-${fillByChar(month)}`
          startDate = `${yearMonthStr}-01`
          endDate = `${yearMonthStr}-${getDaysInMonth(year, month)} 23:59:59`
        }
        this.params['account_date.gte'] = startDate
        this.params['account_date.lte'] = endDate

        this.refresh(true)
        this.getTotalFunds()
      })
    },
    refresh(showLoading = false) {
      this.params.index = 1
      if (showLoading) {
        this.$notice.loading.show()
      }
      this.getData().then(res => {
        console.log(JSON.stringify(res))
        this.data = res
      }).finally(() => {
        this.$refs['list'].refreshEnd()
        if (showLoading) {
          this.$notice.loading.hide()
        }
      })
    },
    loadmore() {
      this.getData().then(res => {
        this.data.push(...res)
      }).finally(() => {
        this.$refs['list'].loadMoreEnd()
      })
    },
    getData() {
      return new Promise((resolve, reject) => {
        this.$api.getData({
          server: 'agr_chain',
          table: 'account_record_day_view',
          params: this.params,
          order: {
            account_date: 'desc'
          }
        }).then(res => {
          this.params.index++
          this.totalPages = (res && res.totalPages) || 0
          const data = ((res && res.data) || []).map(item => {
            item.fundsStr = Number.parseFloat(item.account_funds_total) || 0
            item.records = []
            return item
          })

          // 再次请求当页的详情列表
          if (data.length) {
            const pageEndDate = `${data[0].account_date.substr(0, 10)} 23:59:59`
            const pageStartDate = data[data.length - 1].account_date.substr(0, 10)
            this.getDetailData(pageStartDate, pageEndDate).then(res => {
              resolve(this.fillToData(data, (res || []).map(convert)))
            })
          } else {
            resolve(data)
          }

        }).catch(err => {
          this.totalPages = -1
          reject(err)
        })
      })
    },
    getDetailData(pageStartDate, pageEndDate) {
      return this.$api.getData({
        server: 'agr_chain',
        table: 'account_record_app_view',
        params: {
          'farm_id.eq': this.farm.id,
          'account_date.gte': pageStartDate,
          'account_date.lte': pageEndDate,
          'account_record_type.eq': this.params['account_record_type.eq']
        },
        errorMsg: '获取记账数据失败'
      })
    },
    fillToData(data, res) {
      for (const r of res) {
        const rDay = r.account_date.substr(0, 10)
        for (const d of data) {
          const dDay = d.account_date.substr(0, 10)
          if (rDay === dDay) {
            d.dateStr = r.dateStr
            d.typeStr = r.typeStr
            d.records.push(r)
            break
          }
        }
      }
      return data
    },
    handleTypeSelect() {
      let start = this.params['account_date.gte']
      let end = this.params['account_date.lte']

      if (!start) {
        start = this.$utils.dateFormat(new Date(+new Date - 8.64e7 * 30))
      }
      if (!end) {
        end = this.$utils.dateFormat(new Date())
      }

      this.$dialog.dateRange({
        start,
        end,
        shortcut: true,
        onPositive: ({ ys, ms, ds, ye, me, de }) => {
          const fullNum = num => {
            return +num > 9 ? num : `0${num}`
          }
          ms = fullNum(ms)
          ds = fullNum(ds)
          me = fullNum(me)
          de = fullNum(de)

          this.params['account_date.gte'] = `${ys}-${ms}-${ds} 00:00:00`
          this.params['account_date.lte'] = `${ye}-${me}-${de} 23:59:59`
          this.refresh()
          this.getTotalFunds()
        },
        onDissmiss: () => { },
        onReset: () => {
          this.params['account_date.gte'] = ''
          this.params['account_date.lte'] = ''
          this.refresh()
          this.getTotalFunds()
        }
      })
    },

    // 获取按时间的统计金额
    getTotalFunds() {
      let { index, size, ...totalParams } = this.params
      totalParams.groupFunc = 'sum(account_record_day_view.account_funds_total)'
      this.$api.getData({
        server: 'agr_chain',
        table: 'account_record_day_view',
        params: totalParams,
        errorMsg: '获取统计数据失败'
      }).then(res => {
        this.setNavigationInfo((res && res.length && res[0].p) || 0)
      })
    },

    setNavigationInfo(num) {
      num = Number.parseFloat(num) || 0
      this.$navigator.setNavigationInfo({
        title: `${this.typeStr}合计：${num}`,
        navShow: true,
        statusBarStyle: 'LightContent'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}

.text-success {
  color: $success;
}
.text-error {
  color: $error;
}
.bg-white {
  background-color: #fff;
}

.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.mr-1 {
  margin-right: 5px;
}

.date-picker {
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 25px;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  border-bottom-color: $border-color;
}

.account-icon {
  width: 40px;
  height: 40px;
  margin: 30px;
}
.account-main {
  flex-direction: row;
  flex: 1;
  padding-top: 30px;
  padding-right: 30px;
  padding-bottom: 30;
  border-bottom-width: 1px;
  border-bottom-color: $border-color-light;
  border-bottom-style: solid;
}
.account-main-last {
  border-bottom-width: 0;
}
.account-remark {
  flex: 1;
  font-size: 28px;
  padding-right: 30px;
}
.account-number {
  font-size: 28px;
  min-width: 200px;
}
.account-item {
  flex-direction: row;
  justify-content: space-between;
  padding-top: 20px;
  padding-left: 15px;
  padding-right: 15px;
  padding-bottom: 15px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
  border-bottom-style: solid;
}
.account-date {
  font-size: 24px;
}
</style>
